package com.ruoyi;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;


public class ChatWebSocketHandler extends TextWebSocketHandler {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private static final Set<WebSocketSession> sessions = Collections.synchronizedSet(new HashSet<>());

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        sessions.add(session);
        System.out.println("Connected: " + session.getId());
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        if (redisTemplate == null) {
            throw new IllegalStateException("RedisTemplate is not initialized");
        }

        String payload = message.getPayload();
        if (payload == null) {
            throw new IllegalArgumentException("Payload is null");
        }
        System.out.println("Received: " + payload);

        // 存储消息到 Redis
        redisTemplate.opsForList().rightPush("chatMessages", payload);

        // 广播消息给所有连接的客户端
        synchronized (sessions) {
            for (WebSocketSession webSocketSession : sessions) {
                if (webSocketSession.isOpen()) {
                    webSocketSession.sendMessage(new TextMessage(payload));
                }
            }
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        sessions.remove(session);
        System.out.println("Disconnected: " + session.getId());
    }

}
